package com.xiaoxing.login.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginBehavior;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DeviceUtils;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;
import com.xiaoxing.login.R;
import com.xiaoxing.login.R2;
import com.xiaoxing.login.di.component.DaggerLoginComponent;
import com.xiaoxing.login.di.module.LoginModule;
import com.xiaoxing.login.mvp.contract.LoginContract;
import com.xiaoxing.login.mvp.model.entity.FbLoFgin;
import com.xiaoxing.login.mvp.model.entity.Login;
import com.xiaoxing.login.mvp.model.entity.UpdateUserInfo;
import com.xiaoxing.login.mvp.presenter.LoginPresenter;
import com.xw.repo.XEditText;

import org.json.JSONObject;

import java.util.Arrays;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.armscomponent.commonres.utils.SoftHideKeyBoardUtil;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.BaseConstants;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.ExitUtil;
import me.jessyan.armscomponent.commonsdk.utils.NetworkUtil;
import me.jessyan.armscomponent.commonsdk.utils.Utils;

import static com.jess.arms.utils.Preconditions.checkNotNull;

@Route(path = RouterHub.XIAO_XING_LOGIN_LOGIN_ACTIVITY)
public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View, ShopSelectActivity.UpdateUserInfoI {

    @BindView(R2.id.xet_username)
    XEditText xetUsername;
    @BindView(R2.id.xet_password)
    XEditText xetPassword;
    @BindView(R2.id.img_login)
    TextView btnLogin;
    @BindView(R2.id.ll_root)
    LinearLayout llRoot;
    @BindView(R2.id.img_facebook)
    ImageView img_facebook;
    //    @BindView(R2.id.ll_root)
//    LinearLayout mLLRoot;
    private CallbackManager mCallbackManager;
    private String userId = "";
    private String name = "";

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLoginComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .loginModule(new LoginModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.xiaoxing_login_activity_login; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }


    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        ToolbarUtils.initToolbarTitleNoBack(this, getString(R.string.xiaoxing_login_login));
//        controlKeyboardLayout(mLLRoot, btnLogin);
//        autoLogin();

//        ControlKeyboardLayoutUtil.addLayoutListener(llRoot, img_facebook);
        ShopSelectActivity.setUpdateUserInfoI(this);
        SoftHideKeyBoardUtil.assistActivity(this);
        initFaceBook();
    }

    private void initFaceBook() {

        //创建回调管理器，以便处理登录响应
        mCallbackManager = CallbackManager.Factory.create();

        registerFacebookCallback();
    }

    private void registerFacebookCallback() {

        LoginManager.getInstance().registerCallback(mCallbackManager,
                new FacebookCallback<LoginResult>() {
                    @SuppressWarnings("deprecation")
                    @Override
                    public void onCancel() {
                        System.out.println("onCancel-------------");
                        CookieSyncManager
                                .createInstance(LoginActivity.this);
                        CookieManager cookieManager = CookieManager
                                .getInstance();
                        cookieManager.removeAllCookie();
                        CookieSyncManager.getInstance().sync();
                    }

                    @Override
                    public void onError(FacebookException arg0) {
                        System.out.println("FacebookException-------------");
                    }

                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        System.out.println("LoginResult!!!!!!!!!!-------------" + "登录成功= " + loginResult.getAccessToken());

                        getFacebookInfo(loginResult.getAccessToken());
                    }
                });
    }


    public void getFacebookInfo(AccessToken accessToken) {
        userId = accessToken.getUserId();
        GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(JSONObject object, GraphResponse response) {
                if (object != null) {
                    name = object.optString("name");
//                    goLogin();
                    if (!TextUtils.isEmpty(userId) && !TextUtils.isEmpty(name))
                        mPresenter.fbLogin(userId, name);
                }
            }
        }).executeAsync();
    }

    private void loginFacebook() {
        LoginManager.getInstance().setLoginBehavior(LoginBehavior.WEB_ONLY);
        LoginManager.getInstance().logInWithReadPermissions(
                LoginActivity.this, Arrays.asList("public_profile"));
    }

    @Override
    protected void onActivityResult(final int requestCode,
                                    final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mCallbackManager.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // Logs 'install' and 'app activate' App Events.
//        AppEventsLogger.activateApp(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // Logs 'app deactivate' App Event.
//        AppEventsLogger.deactivateApp(this);
    }

    @Override
    public void showLoading() {
        LoadingDialogUtil.showGifdialog2(getSupportFragmentManager(), R.drawable.public_loading);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtil.dismissDialog();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }


    @OnClick({R2.id.tv_wang_ji_mi_ma, R2.id.tv_hui_yuan_zhu_ce, R2.id.img_login, R2.id.img_facebook})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.tv_hui_yuan_zhu_ce) {
            Utils.navigation(LoginActivity.this, RouterHub.XIAO_XING_LOGIN_REGISTER_SET_PWD_ACTIVITY);
        } else if (view.getId() == R.id.tv_wang_ji_mi_ma) {
            Utils.navigation(LoginActivity.this, RouterHub.XIAO_XING_LOGIN_SET_NEW_PASSWORD_ACTIVITY);
        } else if (view.getId() == R.id.img_login) {
            DeviceUtils.hideSoftKeyboard(this, btnLogin);
            login();
        } else if (view.getId() == R.id.img_facebook) {
//            ArmsUtils.snackbarText("正在開發中...");

            loginFacebook();
        }

    }

    private void login() {
//        if (NetworkUtil.checkNetworkAvailable(this)) {

        if (TextUtils.isEmpty(getUsername())) {
            ArmsUtils.snackbarText("帳戶名/手機號不能為空");
            return;
        }
        if (TextUtils.isEmpty(getPassword())) {
            ArmsUtils.snackbarText("密碼不能為空");
            return;
        }

//        if (getUsername().equals("123") && getPassword().equals("123456")) {//客户测试帐号
//            mSharedPreferencesHelper.putString(BaseConstants.USER_TYPE, "1");
//            Utils.navigation(LoginActivity.this, RouterHub.SALES_CLIENT_KE_HU_DUAN_MAIN_ACTIVITY);
//        } else if (getUsername().equals("456") && getPassword().equals("123456")) {//员工测试帐号
//            mSharedPreferencesHelper.putString(BaseConstants.USER_TYPE, "2");
//            Utils.navigation(LoginActivity.this, RouterHub.SALES_CLIENT_PAI_MAI_MAIN_ACTIVITY);
//
//        } else {
//            ArmsUtils.snackbarText("帳號或密碼錯誤，客戶測試帳號是123，密碼是123456，員工測試帳號是456，密碼是123456");
//            return;
//        }
//        killMyself();
        mPresenter.doLogin(this, getUsername(), getPassword());
//        }
    }

    @NonNull
    private String getPassword() {
        return xetPassword.getText().toString();
    }

    @NonNull
    private String getUsername() {
        return xetUsername.getText().toString();
    }

    @Override
    public void doLoginSuccess(Login login) {
        ArmsUtils.snackbarText(login.getMsg());
        if (login.getCode().equals("200")) {
            mSharedPreferencesHelper.putString(BaseConstants.PASSWORD, getPassword());
            mSharedPreferencesHelper.putBoolean(BaseConstants.IS_LOGIN, true);
            mSharedPreferencesHelper.putString(BaseConstants.IS_STAFF, String.valueOf(login.getData().getIs_staff()));

            //0是用户，1是员工
            if (String.valueOf(login.getData().getIs_staff()).equals("0")) {
                mSharedPreferencesHelper.putString(BaseConstants.TOKEN, login.getData().getMember().getAccess_token());
                mSharedPreferencesHelper.putString(BaseConstants.UID, login.getData().getMember().getUid());
                mSharedPreferencesHelper.putString(BaseConstants.USERNAME, login.getData().getMember().getUser_name());
                mSharedPreferencesHelper.putString(BaseConstants.NICKNAME, login.getData().getMember().getNick_name());
                mSharedPreferencesHelper.putString(BaseConstants.ADDRESS, login.getData().getMember().getAddress());
                mSharedPreferencesHelper.putString(BaseConstants.PHONE, login.getData().getMember().getMobile());
                mSharedPreferencesHelper.putString(BaseConstants.EMAIL, login.getData().getMember().getEmail());
                mSharedPreferencesHelper.putString(BaseConstants.SHOP_ID, login.getData().getMember().getShop_id());
                mSharedPreferencesHelper.putString(BaseConstants.LEVEL, login.getData().getMember().getLevel());
                Utils.navigation(LoginActivity.this, RouterHub.SALES_CLIENT_KE_HU_DUAN_MAIN_ACTIVITY);
            } else {
                mSharedPreferencesHelper.putString(BaseConstants.TOKEN, login.getData().getStaff().getAccess_token());
                mSharedPreferencesHelper.putString(BaseConstants.USERNAME, login.getData().getStaff().getUser_name());
                mSharedPreferencesHelper.putString(BaseConstants.SHOP_ID, login.getData().getStaff().getShop_id());
                Utils.navigation(LoginActivity.this, RouterHub.SALES_CLIENT_PAI_MAI_MAIN_ACTIVITY);

            }
            killMyself();
        }


    }

    private FbLoFgin mFbLoFgin;

    @Override
    public void fbLoginSuccess(FbLoFgin login) {

        ArmsUtils.snackbarText(login.getMsg());
        if (login.getCode().equals("200")) {
            mSharedPreferencesHelper.putString(BaseConstants.PASSWORD, getPassword());
            mSharedPreferencesHelper.putBoolean(BaseConstants.IS_LOGIN, true);
            mSharedPreferencesHelper.putString(BaseConstants.IS_STAFF, String.valueOf(login.getData().getIs_staff()));

            mFbLoFgin = login;
            //0是用户，1是员工
            if (String.valueOf(login.getData().getIs_staff()).equals("0")) {
                mSharedPreferencesHelper.putString(BaseConstants.TOKEN, login.getData().getMember().getAccess_token());
                mSharedPreferencesHelper.putString(BaseConstants.UID, login.getData().getMember().getUid());
                mSharedPreferencesHelper.putString(BaseConstants.USERNAME, login.getData().getMember().getUser_name());
                mSharedPreferencesHelper.putString(BaseConstants.NICKNAME, login.getData().getMember().getNick_name());
                mSharedPreferencesHelper.putString(BaseConstants.ADDRESS, login.getData().getMember().getAddress());
                mSharedPreferencesHelper.putString(BaseConstants.EMAIL, login.getData().getMember().getEmail());
                mSharedPreferencesHelper.putString(BaseConstants.SHOP_ID, login.getData().getMember().getShop_id());
                mSharedPreferencesHelper.putString(BaseConstants.LEVEL, login.getData().getMember().getLevel());

                if (login.getData().getMember().getShop_id().equals("0")) {
                    Utils.navigation(LoginActivity.this, RouterHub.XIAO_XING_LOGIN_SHOP_SELECT_CTIVITY);
                } else {
                    Utils.navigation(LoginActivity.this, RouterHub.SALES_CLIENT_KE_HU_DUAN_MAIN_ACTIVITY);
                    killMyself();
                }
            } else {
                mSharedPreferencesHelper.putString(BaseConstants.TOKEN, login.getData().getStaff().getAccess_token());
                mSharedPreferencesHelper.putString(BaseConstants.USERNAME, login.getData().getStaff().getUser_name());
                mSharedPreferencesHelper.putString(BaseConstants.SHOP_ID, login.getData().getStaff().getShop_id());
                if (login.getData().getStaff().getShop_id().equals("0")) {
                    Utils.navigation(LoginActivity.this, RouterHub.XIAO_XING_LOGIN_SHOP_SELECT_CTIVITY);
                } else {
                    Utils.navigation(LoginActivity.this, RouterHub.SALES_CLIENT_PAI_MAI_MAIN_ACTIVITY);
                    killMyself();
                }

            }
        }

    }


    @Override
    public void updateUserInfoSuccess(UpdateUserInfo updateUserInfo) {
        Utils.navigation(LoginActivity.this, RouterHub.SALES_CLIENT_KE_HU_DUAN_MAIN_ACTIVITY);
        killMyself();
    }

    /**
     * 自动登陆
     */
    public void autoLogin() {
        if (NetworkUtil.checkNetworkAvailable(this)) {

            String username = mSharedPreferencesHelper.getString(BaseConstants.USERNAME);
            String pwd = mSharedPreferencesHelper.getString(BaseConstants.PASSWORD);
            if (username != null && pwd != null) {

                if (BaseConstants.AUTO_LOGIN) {
                    xetUsername.setText(username);
                    xetPassword.setText(pwd);
                    login();
                } else {
                    xetUsername.setText(mSharedPreferencesHelper.getString(BaseConstants.USERNAME));

                }
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ExitUtil.exit(this);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void updateUserInfo(String shopId) {
        if (mFbLoFgin != null) {
            mSharedPreferencesHelper.putString(BaseConstants.SHOP_ID, shopId);
            String nickname = TextUtils.isEmpty(mFbLoFgin.getData().getMember().getNick_name()) ? "" : mFbLoFgin.getData().getMember().getNick_name();
            String address = TextUtils.isEmpty(mFbLoFgin.getData().getMember().getAddress()) ? "" : mFbLoFgin.getData().getMember().getAddress();
            String password = TextUtils.isEmpty(mFbLoFgin.getData().getMember().getPassword()) ? "" : mFbLoFgin.getData().getMember().getPassword();
            String email = TextUtils.isEmpty(mFbLoFgin.getData().getMember().getEmail()) ? "" : mFbLoFgin.getData().getMember().getEmail();
            String mobile = TextUtils.isEmpty(mFbLoFgin.getData().getMember().getMobile()) ? "" : mFbLoFgin.getData().getMember().getMobile();
            mPresenter.updateUserInfo(mSharedPreferencesHelper.getString(BaseConstants.TOKEN)
                    , nickname, address, password, email, mobile, shopId
            );
        }
    }
}
